﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace SqlReader
{
    public partial class SqlReaderService : ServiceBase
    {
        List<SqlReader> watchlist1 = new List<SqlReader>();
        
        public SqlReaderService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        protected override void OnStop()
        {
            for (int i=0; i < watchlist1.Count;i++)
            {
                watchlist1[i].Stop();
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                foreach (ConnectionStringSettings key in ConfigurationManager.ConnectionStrings)
                {
                    if (key.Name.StartsWith("sql"))
                    {
                        SqlReader sqlRead = new SqlReader();
                        sqlRead.Start(key.ToString());
                        watchlist1.Add(sqlRead);
                    }
                }
                
            }
            catch (Exception ex)
            {
                StreamWriter ew = new StreamWriter(ConfigurationManager.AppSettings["ErrorLogPath"].ToString(), true, Encoding.UTF8);
                ew.WriteLine(ex.Message + "\n\r" + ex.InnerException + "\n\r" + ex.StackTrace);
                ew = null;

            }
            finally
            {
                watchlist1 = null;
                
            }
        }

    }
}
